import { createMachine, assign } from 'xstate';

interface ToggleContext {
  count: number;
  maxCount: number;
}

interface ToggleInput {
  maxCount: number;
}

export const toggleMachine = createMachine(
  {
    id: 'toggle',
    context: ({ input }: { input: ToggleInput }): ToggleContext => ({
      count: 0,
      maxCount: input.maxCount,
    }),
    initial: 'inactive',
    states: {
      inactive: {
        on: {
          toggle: [
            {
              guard: 'canToggle',
              target: 'active',
            },
          ],
        },
      },
      active: {
        entry: 'incrementCount',
        on: {
          toggle: 'inactive',
        },
        after: {
          2000: 'inactive',
        },
      },
    },
  },
  {
    actions: {
      incrementCount: assign({
        count: ({ context }: { context: ToggleContext }) => context.count + 1,
      }),
    },
    guards: {
      canToggle: ({ context }: { context: ToggleContext }) => context.count < context.maxCount,
    },
  }
);
